<template>
  <!-- 管理员管理页面 -->
  <div>
    <!-- 搜索表单区域 -->
    <div class="form-container">
      <!-- 状态筛选 -->
      <div class="form-item">
        <span>状态：</span>
        <el-select v-model="status" placeholder="请选择状态" style="width: 150px">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>

      <!-- 账号搜索 -->
      <div class="form-item">
        <span>账号：</span>
        <el-input v-model="account" placeholder="请输入账号" style="width: 150px"></el-input>
      </div>

      <!-- 时间范围筛选 -->
      <div class="form-item">
        <span>时间：</span>
        <div class="time-inputs">
          <el-date-picker v-model="time" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </div>
      </div>

      <!-- 功能按钮 -->
      <div class="form-buttons">
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button type="success" @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 管理员列表表格 -->
    <el-table :data="tableData" border style="width: 100%" class="custom-header-table">
      <el-table-column fixed prop="account" label="管理员账号"></el-table-column>

      <!-- 关联角色信息展示 -->
      <el-table-column label="管理员身份">
        <template slot-scope="scope">
          {{ scope.row.roleDO.roleName }}
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="创建时间"></el-table-column>

      <!-- 状态标签展示 -->
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" type="success">正常</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column fixed="right" label="操作" width="150">
        <template slot-scope="scope">
          <el-button @click="resetAdminPassword(scope.row)" type="text" size="small">重置密码</el-button>
          <!-- 根据状态动态显示按钮 -->
          <el-button @click="toggleAdminStatus(scope.row)" type="text" size="small"
            :style="{ color: scope.row.status === 0 ? '#F56C6C' : '#67C23A' }">
            {{ scope.row.status === 0 ? '封禁' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

  </div>
</template>

<script>
// 导入接口方法，注意：这里假设你有一个updateAdminStatus接口
import { selectAdminsByCondition, resetPassword, updateAdminStatus } from "@/api/admin";
export default {
  data() {
    return {
      time: [], // 时间范围选择器绑定值
      adminId: null,
      account: '', // 账号搜索关键词
      roleName: '',
      createTime: '',
      status: '', // 状态筛选值
      startTime: null, // 开始时间（内部处理用）
      endTime: null, // 结束时间（内部处理用）

      currentPage: 1, // 当前页码
      pageSize: 5, // 每页条数
      total: 0, // 总记录数

      // 状态选项数据
      options: [
        { value: 0, label: '正常' },
        { value: 1, label: '禁用' }
      ],

      tableData: [] // 表格数据源
    }
  },
  methods: {
    handleClick(row) {
      console.log(row);
    },
    // 执行查询
    handleSearch() {
      const params = {
        account: this.account,
        roleName: this.roleName,
        createTime: this.createTime,
        status: this.status,
        startTime: this.startTime,
        endTime: this.endTime,
        currentPage: this.currentPage,
        pageSize: this.pageSize,
      };
      this.loadData(params);
    },

    // 重置查询条件
    handleReset() {
      this.status = '';
      this.account = '';
      this.time = [];
      this.startTime = null;
      this.endTime = null;
      this.currentPage = 1;
      this.handleSearch();
    },

    // 分页大小变更
    handleSizeChange(val) {
      this.pageSize = val;
      this.handleSearch();
    },
    // 页码变更
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handleSearch();
    },

    // 重置密码
    resetAdminPassword(row) {
      this.$confirm(`是否确定重置管理员 "${row.account}" 的密码？`, "确认重置", {
        confirmButtonText: "确定重置",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          resetPassword(row.adminId)
            .then(response => {
              if (response.code === 200) {
                this.$message.success("管理员密码重置成功！");
                this.handleSearch();
              } else {
                this.$message.error("重置失败：" + response.msg);
              }
            })
            .catch(error => {
              this.$message.error("请求失败：" + error.message);
            });
        })
        .catch(() => {
          this.$message.info("已取消密码重置操作");
        });
    },

    // 切换管理员状态（封禁/启用）
    toggleAdminStatus(row) {
      // 根据当前状态确定操作类型和新状态值
      const isDisable = row.status === 0;
      const operation = isDisable ? '封禁' : '启用';
      const newStatus = isDisable ? 1 : 0;

      this.$confirm(`是否确定${operation}管理员 "${row.account}"？`, `确认${operation}`, {
        confirmButtonText: `确定${operation}`,
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 调用更新状态的接口，传递管理员ID和新状态
          updateAdminStatus({
            adminId: row.adminId,
            status: newStatus
          })
            .then(response => {
              if (response.code === 200) {
                this.$message.success(`管理员${operation}成功！`);
                // 重新加载数据以更新表格显示
                this.handleSearch();
              } else {
                this.$message.error(`${operation}失败：` + response.msg);
              }
            })
            .catch(error => {
              this.$message.error("请求失败：" + error.message);
            });
        })
        .catch(() => {
          this.$message.info(`已取消${operation}操作`);
        });
    },

    // 加载表格数据
    async loadData(params) {
      try {
        const response = await selectAdminsByCondition(params);
        this.tableData = response.data.list || [];
        this.total = response.data.total;
      } catch (error) {
        console.error("数据加载失败:", error);
        this.$message.error("加载数据失败，请稍后重试");
      }
    }
  },

  // 页面初始化时加载数据
  created() {
    this.handleSearch();
  },

  // 监听时间范围变化，拆分开始/结束时间
  watch: {
    time(newVal) {
      if (newVal && newVal.length === 2) {
        this.startTime = newVal[0];
        this.endTime = newVal[1];
      } else {
        this.startTime = null;
        this.endTime = null;
      }
    },
  },
}
</script>

<style scoped>
/* 表单容器样式 */
.form-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 15px;
}

/* 表单项样式 */
.form-item {
  display: flex;
  align-items: center;
}

.form-item span {
  margin-right: 8px;
  white-space: nowrap;
}

/* 时间选择器容器 */
.time-inputs {
  display: flex;
  gap: 10px;
}

/* 按钮组样式 */
.form-buttons {
  display: flex;
  gap: 10px;
  align-items: center;
}

/* 分页样式 */
.pagination-left {
  margin-top: 10px;
  text-align: left;
}

/* 表头样式 */
.custom-header-table ::v-deep .el-table__header th {
  height: 48px;
  line-height: 48px;
  padding: 0;
  background-color: #f5f7fa;
  font-weight: bold;
}

.custom-header-table ::v-deep .el-table__header .cell {
  line-height: 48px;
}
</style>
